package com.xsy.de.restful.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xsy.de.entity.ResultMsg;
import com.xsy.de.entity.User;
import com.xsy.de.service.UserService;
import io.swagger.annotations.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/rest/sys")
@Api(tags="用户接口", description = "提供用户注册，用户登录功能")
public class LoginRestController {
    private final static Logger log = LogManager.getLogger(LoginRestController.class);

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     * @param userName
     * @param userPwd
     * @return
     */
    @ApiOperation(value="用户注册", notes="输入手机号和密码来注册,rtncode=0注册成功，非0注册失败")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName",value = "用户名（手机号）", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "userPwd",value = "密码", required = true, dataType = "string",paramType = "query"),
    })@RequestMapping(value = "/reg", method = RequestMethod.POST, produces= MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultMsg regUser(@RequestParam String userName, @RequestParam String userPwd) {
        log.info("rest接口用户注册：" + userName + "=" + userPwd);
        ResultMsg resultMsg = new ResultMsg();
        JSONObject userInfo = new JSONObject();
        try {
            //查询注册用户是否已存在
            QueryWrapper<User> queryWrapperF = new QueryWrapper<User>();
            queryWrapperF.eq("USER_NAME", userName);
            List<User> users = userService.selectList(queryWrapperF);
            if (users.size() > 0){
                resultMsg.setRtncode("2");
                resultMsg.setErrmsg("该用户已注册");
                return resultMsg;
            }
            User user = new User();
            user.setUserName(userName);
            user.setUserPwd(userPwd);
            user.setStatus("1");
            user.setCreateDate(LocalDateTime.now());
            boolean result = userService.insert(user);
            if (result){
                log.info("rest接口用户注册成功：" + userName + "=" + userPwd);
                QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
                queryWrapper.eq("USER_NAME", userName);
                User newUser = userService.selectOne(queryWrapper);
                userInfo.put("id",newUser.getId());
                userInfo.put("userName",newUser.getUserName());
                userInfo.put("createDate",newUser.getCreateDate());
                resultMsg.setRtncode("0");
                resultMsg.setRtninfo(userInfo);
                resultMsg.setErrmsg("注册成功");
            }else {
                resultMsg.setRtncode("1");
                resultMsg.setErrmsg("注册失败，请稍后重试");
            }
        }catch (Exception e) {
            resultMsg.setRtncode("9");
            resultMsg.setErrmsg("注册失败，系统错误：" + e.getMessage());
            log.error(userName + ":rest接口注册失败，系统错误：" + e.getMessage());
            e.printStackTrace();
        }
        return resultMsg;

    }

    /**
     * 用户登录
     * @param userName
     * @param userPwd
     * @return
     */
    @ApiOperation(value="用户登录", notes="使用用户名和密码登录,rtncode=0登录成功，非0登录失败")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName",value = "用户名（手机号）", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "userPwd",value = "密码", required = true, dataType = "string",paramType = "query"),
    })
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces= MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultMsg loginUser(@RequestParam String userName, @RequestParam String userPwd) {
        log.info("rest接口用户登录：" + userName);
        ResultMsg resultMsg = new ResultMsg();
        JSONObject userInfo = new JSONObject();
        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
            queryWrapper.eq("USER_NAME", userName);
            queryWrapper.eq("USER_PWD", userPwd);
            List<User> users = userService.selectList(queryWrapper);
            if (users.size() > 0){
                userInfo.put("id",users.get(0).getId());
                userInfo.put("userName",users.get(0).getUserName());
                userInfo.put("createDate",users.get(0).getCreateDate());
                resultMsg.setRtncode("0");
                resultMsg.setRtninfo(userInfo);
                resultMsg.setErrmsg("登录校验通过");
            }else {
                resultMsg.setRtncode("1");
                resultMsg.setErrmsg("登录失败，用户名或密码错误");
            }
        }catch (Exception e) {
            resultMsg.setRtncode("9");
            resultMsg.setErrmsg("登录失败，系统错误：" + e.getMessage());
            log.error(userName + "rest接口登录失败，系统错误：" + e.getMessage());
            e.printStackTrace();
        }
        return resultMsg;

    }

    /**
     * 用户登录
     * @param userName
     * @param userPwd
     * @return
     */
//    @ApiOperation(value = "登录接口-多值传输方式", notes = "输入用户名和密码登录")
//    @ApiResponses(value = {
//            @ApiResponse(code = 200, message = "OK", response = ResultMsg.class, responseContainer = "ResultMsg"),
//            @ApiResponse(code = 405, message = "用户名名或密码错误")
//    })
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "userName",value = "用户名", required = true, dataType = "string", paramType = "query"),
//            @ApiImplicitParam(name = "userPwd",value = "密码", required = true, dataType = "string",paramType = "query"),
//    })
//    @RequestMapping(value = "/login2", method = RequestMethod.POST, produces= MediaType.APPLICATION_JSON_UTF8_VALUE)
//    public ResponseEntity<ResultMsg> loginUser2(@RequestParam String userName, @RequestParam String userPwd) {
//        ResultMsg resultMsg = new ResultMsg();
//        JSONObject userInfo = new JSONObject();
//        try {
//            QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
//            queryWrapper.eq("USER_NAME", userName);
//            queryWrapper.eq("USER_PWD", userPwd);
//            List<User> users = userService.selectList(queryWrapper);
//            if (users.size() > 0){
//                userInfo.put("id",users.get(0).getId());
//                userInfo.put("userName",users.get(0).getUserName());
//                userInfo.put("createDate",users.get(0).getCreateDate());
//                resultMsg.setRtncode("0");
//                resultMsg.setRtninfo(userInfo);
//                resultMsg.setErrmsg("登录校验通过");
//            }else {
//                resultMsg.setRtncode("1");
//                resultMsg.setErrmsg("登录失败，用户名或密码错误");
//                return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).build();
//            }
//        }catch (Exception e) {
//            resultMsg.setRtncode("9");
//            resultMsg.setErrmsg("登录失败，系统错误：" + e.getMessage());
//            e.printStackTrace();
//        }
//        return ResponseEntity.ok(resultMsg);
//
//    }
}
